<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;
use Common\Common\Api\Redis\Websiteconfig;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 马币
 */
class Dongfang2Controller extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = [];
        $data['api_id'] = $this->config['mch_id'];

        switch($this->config['paytype']){
            case 1:
            case 2:
            case 23:
            case 24:
                $data['payment'] = 'wechat.scan';
                break;
            case 3:
            case 4:
            case 17:
            case 18:
            case 21:
            case 22:
                $data['payment'] = 'alipay.scan';
                break;
            case 11:
                $data['payment'] = 'bank.unionpay';
                break;
            default:
                $this->showmessage('此通道暂不支持此产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $data['amount'] = $this->getAmount($return['amount']);
        $data['order_no'] = $return['orderid'];

        $arr = [
            //马币
            'mabi' => 'MYR',
            //新加坡
            'xjp' => 'SGD',
            //美元
            'my' => 'USD',
            //泰铢
            'taizhu' => 'THB',
        ];
        $data['currency'] = $arr[$this->config['appid']];
        //$data['content'] = 'dongfang';
        $data['content'] = "EAST-A5-7u-".mt_rand(10000000,99999999);
        $data['timestamp'] = time();
        $data['version'] = 'v2';
        $data['token'] = $this->getSign($data);

        $res = curl($this->config['gateway'], httpstr($data));
        $res = json_decode($res, true);

        /*echo "<pre/>"; print_r($data);
        echo "请求地址：" . $this->config['gateway'].'<br/>';
        print_r($res); exit;*/

        $code = $res['callback'];

        if(!$code){
            if($res['response'] && is_string($res['response'])){
                $this->showmessage($res['response'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        if($isMobile && $this->config['appid'] == 'xjp' && in_array($this->config['paytype'],[1,2,23,24])){
            $code = substr($code,-(strpos($code,'text')+5));
            header("Location:{$code}"); exit;
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        //$this->assign("wap_url", $code);
        $this->assign("code_url", $code);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        //$this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //微信
            case 1:
            case 2:
            case 23:
            case 24:
                if(!$isMobile){
                    $this->display("WeiXin/weixin");
                }else{
                    //header("Location:{$code}"); exit;
                    $this->display("WeiXin/weixinwap");
                }
                break;
            case 3:
            case 4:
            case 17:
            case 18:
            case 21:
            case 22:
                $this->assign("deny_layer",1);
                if(!$isMobile){
                    $this->display("WeiXin/alipay");
                }else{
                    $this->display("WeiXin/alipaywap");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    private function getAmount($money){
        $appid = $this->config['appid'];

        if(!$appid){
            $this->showmessage('通道APPID设置有误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        //马币汇率
        $config = Websiteconfig::getInstance()->getById(1);

        switch($this->config['paytype']){
            case 1:
            case 2:
            case 23:
            case 24:
                //微信汇率
                $appid = $appid . '2';
                break;
            case 3:
            case 4:
            case 17:
            case 18:
            case 21:
            case 22:
                //支付宝汇率
                break;
            default:
                $this->showmessage('暂不支持此通道的汇率转换!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        if(!isset($config[$appid])){
            $this->showmessage('通道APPID设置有误2!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        if($config[$appid] == 0){
            $this->showmessage('请先设置汇率!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        return number_format($money / $config[$appid],2,'.','');
    }

    private function getSign($data){
        ksort($data);

        $arr = [];
        foreach($data as $k=>$v){
            if($v==='' || in_array($k,['token'])){
                continue;
            }

            $arr[$k] = $v;
        }
        $string = join('', $arr);

        //$token = md5($api_id.md5(md5($string).$parameter['timestamp']).$api_key);

        //$str = $arr['api_id'] . md5(md5($string).$arr['timestamp']) . $this->config['signkey'];
        $str = $this->config['mch_id'] . md5(md5($string).$arr['timestamp']) . $this->config['signkey'];

        return md5($str);
    }

    //通知
    public function notifyurl(){
		//$this->debug_callback();
        if(!$this->checkip(getIP(),['34.92.57.198'])){
            exit("STATUS:MIUPAYOK");
        }
        $p = I("post.");

        //$p = array ( 'order_id' => 'yP9JVpr6o1oOr10OZBmEkx1560410335', 'order_no' => '2019061315185438966', 'amount' => '20.0000', 'currency' => 'MYR', 'pay_currency' => 'CNY', 'pay_amount' => '33.4400', 'rate' => '1.671921', 'status' => '100', 'timestamp' => '1560410383', 'token' => 'c17e3747bd829b33315fcc13aa4c7af5', );

        if(!$p || empty($p)){
            exit("STATUS:MIUPAYOK");
        }

        //获取订单信息
        $orderid = $p['order_no'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'STATUS:MIUPAYOK'; exit;
        }

        //保存回调数据
        if($p['status'] === '100'){
            M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
                "pay_orderid_rd"=>htmlspecialchars($p['order_id']),
                "pay_true"=>floatval($p['pay_amount']),
            ));

            //如果(原金额-实际支付金额) / 实际支付金额大于 0.05 的话会亏本
            if((abs($p['pay_amount'] - $find['pay_amount']) / $find['pay_amount']) >= 0.015){
                $this->closeTongdao($find);
            }
        }else{
            M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
                "pay_orderid_rd"=>htmlspecialchars($p['order_id']),
            ));
        }

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['token'];
        $sign2 = $this->getSign($p);

        if($sign !== $sign2){
            exit("STATUS:MIUPAYOK");
        }

        if($p['status'] !== '100'){
            exit("STATUS:MIUPAYOK");
        }

        $this->async($find['pay_orderid'],"STATUS:MIUPAYOK");
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }

    private function closeTongdao($find){
        $channel = Channel::getInstance()->find(['title'=>$find['pay_yzh_tongdao']]);

        if($channel){
            $product = Product::getInstance()->find(['paytype'=>$channel['paytype']]);
            if(!$product){
                return false;
            }
        }

        $t = explode("|", $product['weight']);
        $arr = array();
        foreach($t as $k=>$v){
            $tmp = explode(":", $v);
            if($tmp[0] != $channel['id']){
                $arr[] = $tmp;
            }
        }

        if(empty($arr)){
            M("Product")->where(array("id"=>$product['id']))->save(array("status"=>0,"weight"=>""));
            Product::getInstance()->edit($product['id'], ['status'=>0,'weight'=>'']);
        }else{
            $str = "";
            foreach($arr as $k=>$v){
                $str .= implode(":",$v)."|";
            }
            $str = substr($str,0,-1);

            M("Product")->where(array("id"=>$product['id']))->save(array("weight"=>$str));
            Product::getInstance()->edit($product['id'], ['weight'=>$str]);
        }
    }
}